﻿using DotNetProject.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;

namespace DotNetProject.Controllers
{
    public class MovieController : Controller
    {
        MovieViewerDb _db = new MovieViewerDb();

        public ActionResult Autocomplete(string term)
        {
            var model = _db.Movies
                .Where(r => r.movieTitle.StartsWith(term))
                .Take(10)
                .Select(r => new{label = r.movieTitle});
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Index(string searchTermMovie, int page = 1)
        {
            var model = _db.Movies
                .OrderByDescending(r => r.movieReleaseDate)
                .Where(r => searchTermMovie == null || r.movieTitle.StartsWith(searchTermMovie))
                .ToPagedList(page, 10);

            if (Request.IsAjaxRequest())
            {
                return PartialView("_MovieLijst", model);
            }

            return View(model);
        }

        public ActionResult Details(int id = 0)
        {
            Movie movie = _db.Movies.Find(id);
            if (movie == null)
            {
                return HttpNotFound();
            }
            return View(movie);
        }

        [HttpPost]
        public ActionResult Details(Review review)
        {
            if (ModelState.IsValid)
            {
                _db.Reviews.Add(review);
                _db.SaveChanges();
                return RedirectToAction("Index", new { id = review.movieId });
            }
            return View(review);
        }

        protected override void Dispose(bool disposing)
        {
            if (_db != null)
            {
                _db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
